<template>
  <div style="padding-bottom: 10px">
    <!-- 查询 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="taskStatus">
        <el-select v-model="queryParams.taskStatus" placeholder="请选择任务状态" clearable size="small">
          <el-option
            v-for="dict in taskStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标注类型" prop="markType">
        <el-select v-model="queryParams.markType" placeholder="请选择标注类型" clearable size="small">
          <el-option
            v-for="dict in markTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 批量操作 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="task == null">
        <el-button plain icon="el-icon-plus" size="mini" @click="handleAddClick" v-hasPermi="['mark:qatask:add']"
          >创建</el-button
        >
      </el-col>

      <template v-else>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-edit"
            size="mini"
            @click="handleBatch"
            v-show="checkRoleMethod(['admin'])"
            :disabled="multiple"
            >批量修改任务配置</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-edit"
            size="mini"
            @click="handleBatchSummarize"
            v-show="checkRoleMethod(['admin'])"
            :disabled="multiple"
            >批量汇总</el-button
          >
        </el-col>
      </template>
    </el-row>

    <el-table v-loading="loading" :data="qaTaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="checkboxSelect" />

      <el-table-column label="名称">
        <template slot-scope="scope">
          <template v-if="scope.row.taskName">
            <el-button
              circle
              type="warning"
              size="mini"
              icon="el-icon-folder"
              @click="enterTask(scope.row)"
            ></el-button>
            <el-button size="mini" type="text" @click="enterTask(scope.row)">{{ scope.row.taskName }}</el-button>
          </template>

          <template v-else>
            <!-- v-show="scope.row.fileId" -->
            <el-button
              circle
              size="mini"
              type="success"
              icon="el-icon-document"
              @click="enterOnlineCheck(scope.row)"
            ></el-button>
            <el-button size="mini" type="text" @click="enterOnlineCheck(scope.row)">{{ scope.row.fileId }}</el-button>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" prop="status" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.taskName">
            <el-tag v-if="scope.row.workflow"> {{ statusFormat(scope.row) }}</el-tag>
          </template>
        </template>
      </el-table-column>
      <!-- <el-table-column label="状态" width="100" prop="taskStatus" :formatter="taskStatusFormat" /> -->
      <!--el-table-column label="任务类型" prop="taskType" :formatter="taskTypeFormat" /-->
      <el-table-column label="标注类型" width="100" prop="markType" :formatter="markTypeFormat" />
      <el-table-column label="操作" width="240" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <task-operation-buttons
            :task="scope.row"
            type="text"
            size="mini"
            @updated="handleStatusChanged"
            v-bind="taskOperFn"
            v-if="scope.row.taskName"
          >
            <template v-slot:assignBtn="{ workflow, type, size }">
              <el-button :size="size" :type="type" icon="el-icon-edit" @click="handleAssign(workflow)">指派</el-button>
            </template>
          </task-operation-buttons>
        </template>
      </el-table-column>
      <el-table-column label="浏览" width="240" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateClick(scope.row)"
            v-show="scope.row.taskName && checkRoleMethod(['admin'])"
            v-hasPermi="['mark:qatask:edit']"
            >配置</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-notebook-2"
            @click="handleListFile(scope.row)"
            v-show="scope.row.taskName"
            >列表</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleTaskReport(scope.row)"
            v-show="scope.row.taskName"
            >统计</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleDelete(scope.row)"
            v-show="scope.row.taskName && checkRoleMethod(['admin'])"
            v-hasPermi="['mark:qatask:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > queryParams.pageSize"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改验收任务对话框 -->
    <task-form-dialog
      v-hasPermi="['mark:qatask:edit']"
      ref="taskFormDialog"
      v-bind="dictOptions"
      @submit="submitTaskForm"
    ></task-form-dialog>

    <!-- 批量修改任务状态对话框 -->
    <task-batch-dialog
      v-hasPermi="['mark:qatask:edit']"
      ref="taskBatchDialog"
      :parent="task"
      v-bind="dictOptions"
      @submit="submitBatchForm"
    ></task-batch-dialog>
  </div>
</template>

<script>
import {
  listQaTask,
  getQaTask,
  updateQaTaskStatus,
  delQaTask,
  addQaTask,
  updateQaTask,
  batchUpdate,
  summarize,
  batchSummarize,
  taskAutoCheck,
} from '@/api/mark/qaTaskV1'
import { assignTask } from '@/api/task/workflow'

import { formatTaskStatus } from '@/utils/workflow'
import { treeselect, listDept } from '@/api/system/dept'

import { checkRole, checkPermi } from '@/utils/permission'
import TaskOperationButtons from './TaskOperationButtons.vue'
import TaskBatchDialog from './dialog/TaskBatchDialog.vue'
import TaskFormDialog from './dialog/TaskFormDialog.vue'

const ROUTE_PATH = Object.freeze({
  editor_2d: '/mark/editor2dv1',
  radar_view: '/mark/RadarViewV1',
  mark_result: '/mark/result',
})

const treeToList = (treeList) => {
  const list = []
  treeList.forEach((element) => {
    const newItem = { id: element.id, label: element.label }
    list.push(newItem)
    if (element.children) {
      const children = treeToList(element.children)
      Array.prototype.push.apply(list, children)
    }
  })
  return list
}

const filterFactoryOptions = (options, task) => {
  if (task) {
    const listOptions = treeToList(options)
    console.log(listOptions)
    return listOptions.filter((option) => task.factoryIds.includes(option.id))
  } else {
    return options
  }
}

export default {
  components: { TaskOperationButtons, TaskBatchDialog, TaskFormDialog },
  name: 'TaskTreeList',

  props: {
    task: { type: Object },
  },

  computed: {
    taskOperFn() {
      const func = {}
      for (const k in this.$attrs) {
        if (k.startsWith('task') && k.endsWith('fn') && this.$attrs[k] instanceof Function) {
          func[k] = this.$attrs[k]
        }
      }
      return func
    },

    dictOptions() {
      return {
        taskStatusOptions: this.taskStatusOptions,
        taskTypeOptions: this.taskTypeOptions,
        markTypeOptions: this.markTypeOptions,
        deptOptions: this.deptOptions,
        factoriesOptions: filterFactoryOptions(this.factoriesOptions, this.task),
      }
    },
  },

  watch: {
    $route: {
      immediate: true,
      handler(to, from) {
        this.refresh()
      },
    },
  },
  data() {
    return {
      listMethod: undefined,

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 验收任务表格数据
      qaTaskList: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        parentId: 0,
        taskName: undefined,
        orderNum: undefined,
        taskStatus: undefined,
        markType: undefined,
      },

      // 任务状态字典
      taskStatusOptions: [],
      // 任务类型：0：全检；1：抽检字典
      taskTypeOptions: [],
      // 标注类型字典
      markTypeOptions: [],
      deptOptions: [],
      factoriesOptions: [],
    }
  },
  created() {
    // this.refresh()
    this.initOptions()
  },

  methods: {
    checkRole,
    checkPermi,

    initOptions() {
      this.getDicts('mark_qa_task_status').then((response) => {
        this.taskStatusOptions = response.data
      })
      this.getDicts('mark_qa_task_type').then((response) => {
        this.taskTypeOptions = response.data
      })
      this.getDicts('mark_type').then((response) => {
        this.markTypeOptions = response.data
      })
      if (checkPermi(['mark:qatask:edit'])) {
        treeselect('0').then((response) => {
          this.deptOptions = response.data
        })
        treeselect('1').then((response) => {
          this.factoriesOptions = response.data
        })
      }
    },

    refresh() {
      this.queryParams.parentId = 0
      if (this.$route.query.taskId || this.$route.query.taskId === 0) {
        this.queryParams.parentId = this.$route.query.taskId
        if (this.$store.getters.queryTask[this.queryParams.parentId]) {
          this.queryParams = this.$store.getters.queryTask[this.queryParams.parentId]
        } else {
          this.queryParams.pageNum = 1
          this.resetForm('queryForm')
        }
      }
      this.getList()
    },

    handleStatusChanged() {
      console.log('updated status')
      this.getList()
    },

    checkRoleMethod(role) {
      return checkRole(role)
    },
    /** 查询验收任务列表 */
    getList() {
      this.loading = true
      this.$store.dispatch('queryTaskCached', this.queryParams)
      listQaTask(this.queryParams).then((response) => {
        this.qaTaskList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    enterTask(row) {
      this.$router.push({
        path: '/mark/task',
        query: { taskId: row.taskId },
      })
    },
    enterOnlineCheck(row) {
      if (row.markType == '0') {
        this.$router.push({
          path: '/mark/pointCloudSplit',
          query: {
            taskId: row.taskId,
            mQaResultId: row.mQaResultId,
          },
        })
      } else {
        console.log(row.taskId)
        this.$router.push({
          path: ROUTE_PATH.editor_2d,
          query: {
            taskId: row.taskId,
            mQaResultId: row.mQaResultId,
          },
        })
      }
    },

    // 任务状态字典翻译
    // taskStatusFormat(row, column) {
    //   return this.selectDictLabel(this.taskStatusOptions, row.taskStatus)
    // },

    statusFormat(row) {
      return formatTaskStatus({ taskStatus: row.status })
    },
    // 任务类型：0：全检；1：抽检字典翻译
    taskTypeFormat(row, column) {
      return this.selectDictLabel(this.taskTypeOptions, row.taskType)
    },
    // 标注类型字典翻译
    markTypeFormat(row, column) {
      return this.selectDictLabel(this.markTypeOptions, row.markType)
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.taskId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    checkboxSelect(row) {
      if (row.taskName) {
        return 1
      }
    },

    /** 新增按钮操作 */
    handleAddClick() {
      this.$refs.taskFormDialog.add()
    },

    /** 修改按钮操作 */
    handleUpdateClick(row) {
      getQaTask(row.taskId).then((response) => {
        const task = response.data
        this.$refs.taskFormDialog.edit(task)
      })
    },
    /** 提交按钮 */
    submitTaskForm(task) {
      const submitFn = task.taskId ? updateQaTask : addQaTask
      const message = task.taskId ? '修改成功' : '新增成功'
      submitFn(task).then((response) => {
        if (response.code === 200) {
          this.msgSuccess(message)
          this.$refs.taskFormDialog.close()
          this.getList()
        } else {
          this.msgError(response.msg)
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.taskId || this.ids
      this.$confirm('是否确认删除选中的任务?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return this.$confirm(
            '再次确认，该任务下所有子任务和标注结果都将被删除，且此删除操作不可恢复！仍要删除？',
            '警告',
            { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
          )
        })
        .then(() => {
          return delQaTask(taskIds)
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(console.error)
    },

    handleListFile(row) {
      this.$router.push({ path: '/mark/result', query: { taskId: row.taskId, pageNum: 1 } })
    },
    handleTaskReport(row) {
      this.$router.push({ path: '/mark/report', query: { taskId: row.taskId, pageNum: 1 } })
    },

    // 批量操作
    handleBatch() {
      this.$refs['taskBatchDialog'].open()
    },
    submitBatchForm(data) {
      data.taskIds = this.ids
      console.log(data)
      batchUpdate(data)
        .then((response) => {
          if (response.code === 200) {
            this.msgSuccess(response.msg)
            this.$refs.taskBatchDialog.close()
            this.getList()
          } else {
            this.msgError(response.msg)
          }
        })
        .catch(console.error)
    },

    // 批量汇总
    handleBatchSummarize(row) {
      let para = { taskIds: this.ids }
      batchSummarize(para).then((response) => {
        if (response.code === 200) {
          this.msgSuccess(res.msg)
        } else {
          this.msgError(res.msg)
        }
      })
    },
  },
}
</script>
